// 流量消耗
import React, { useState, memo, useEffect, useCallback } from 'react';
import { Table, Row, Col, Alert } from 'tdesign-react';
import { useNavigate } from 'react-router-dom';
import { getListApi } from 'api/useManage/flowExpendStatistics';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import useTableSort from 'hooks/useTableSort';
import { USER_TYPE_MAP, USER_TYPE_OPTIONS } from 'constants/index';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import IppeakTable from 'components/IppeakTable';
import { createRequestParams } from 'utils';

// 初始查询参数
const INITIAL_QUERY = {
  page: 1,
  page_size: 10,
  username: '',
  tags: '',
  type:1
};

// 初始表格状态
const INITIAL_TABLE_STATE = {
  list: [],
  total: 0,
  current: 1,
  pageSize: 10,
};

export const SelectTable = () => {
  const navigate = useNavigate();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, setLoading } = useLoading(false);
  const [hideQuerys, sethideQuerys] = useState({
    qudao: true,
    tuiguang: true,
  });

  // 表格状态管理
  const [table, setTable] = useState(INITIAL_TABLE_STATE);
  const [query, setQuery] = useState(INITIAL_QUERY);

  // 排序功能
  const { sortState, handleSort, sortedData } = useTableSort({
    onSortChange: (sortKey, sortOrder) => {
      // 这里可以触发重新请求数据，或者对本地数据进行排序
    },
  });

  const { list, total } = table;

  // 表格列定义
  const columns = createColumns([
    {
      label: '用户ID',
      key: 'si_user_id',
      width: '70',
    },
    {
      label: '邮箱',
      key: 'name',
      width: 180,
    },
    {
      label: '消耗日期',
      key: 'use_date',
      type: 'date',
      format: 'YYYY-MM-DD',
    },
    {
      label: '目标网站数',
      key: 'target_count',
    },
    {
      label: '连接数',
      key: 'total_count',
      width: '80',
    },
    {
      label: '成功数',
      key: 'success_count',
      width: '140',
    },
    {
      label: '失败数',
      width: '120',
      key: 'fail_count',
    },
    {
      label: '成功率',
      key: 'success_rate',
      width: '150',
      render: ({ row }: any) => <span>{row.success_rate}%</span>,
    },
    {
      label: '消耗流量',
      key: 'traff_count_real',
      width: '140',
      align: 'center',
      sortable: true, // 启用排序
    },
    {
      label: '操作',
      key: 'op',
      buttons: [
        {
          text: '查看消耗明细',
          onClick: (row: any) => {
            navigate(`/useManage/flowExpendStatistics/detail/${row.si_user_id}`, {
              state: {
                username: row.name,
                date:row.use_date,
              },
            });
          },
        },
      ],
    },
  ], {
    currentSortKey: sortState.sortKey || undefined,
    currentSortOrder: sortState.sortOrder || undefined,
    onSort: handleSort,
  });

  // 表单字段定义
  const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 50,
      },
    },
  ];

  const fetchTableList = useCallback(
    async (params?: any) => {
      setLoading(true);
      try {
        // 合并参数并过滤空值
        const requestParams = createRequestParams({ ...params, ...query });
        const res: any = await getListApi(requestParams);
        setLoading(false);
        setTable((pre: any) => ({
          ...pre,
          list: res.results || [],
          total: res.total || 0,
          current: requestParams.page || query.page,
          pageSize: requestParams.page_size || query.page_size,
        }));
      } catch (err) {
        console.log(err, 'err');
        setLoading(false);
      }
    },
    [query],
  );

  // 处理选择变化
  const onSelectChange = useCallback((value: (string | number)[]) => {
    setSelectedRowKeys(value);
  }, []);

  // 处理搜索
  const handleSearch = useCallback((values: any) => {
    setQuery((pre) => ({
      ...pre,
      ...values,
      page: 1,
    }));
    setTable((pre) => ({
      ...pre,
      current: 1,
    }));
  }, []);

  // 处理重置
  const handleReset = useCallback(() => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
      type:1
    }));
  }, []);

  // 处理分页变化
  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setQuery((pre) => ({
      ...pre,
      page,
      page_size: pageSize,
    }));
    setTable((pre) => ({
      ...pre,
      current: page,
      pageSize: pageSize,
    }));
  }, []);

  // 处理当前页变化
  const handleCurrentChange = useCallback(
    (current: number, pageInfo: any) => {
      handlePaginationChange(pageInfo.current, table.pageSize);
    },
    [table.pageSize, handlePaginationChange],
  );

  // 处理每页条数变化
  const handlePageSizeChange = useCallback(
    (size: number) => {
      handlePaginationChange(1, size); // 切换每页条数时重置到第一页
    },
    [handlePaginationChange],
  );

  // 获取排序后的数据
  const sortedList = sortedData(list, sortState.sortKey, sortState.sortOrder);

  // 操作相关函数
  const rehandleClickOp = useCallback((record: any) => {
  }, []);

  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  // 监听查询参数变化，自动获取数据
  useEffect(() => {
    fetchTableList();
  }, [fetchTableList]);
    // 统一的字段清除处理函数
    const handleFieldClear = (fieldName: string) => {
      setQuery((prev: any) => {
        const { [fieldName]: removed, ...rest } = prev || {};
        return { ...rest, };
      });
    };
  return (
    <>
      {/* <Alert style={{background:'#fff',fontSize:'16px',color:'#999',padding:'0',marginBottom:'10px'}} message="重点关注ID：4346、4888、4542、4747、4755"  /> */}
      <Row>
        <Col>
          <SakuraSearchForm fields={formFields} onSearch={handleSearch} 
          onFieldClear={handleFieldClear}
          onReset={handleReset} />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={sortedList}
        columns={columns}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        tableHeight={272}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: table.pageSize,
          total,
          current: table.current,
          showJumper: true,
          onCurrentChange: handleCurrentChange,
          onPageSizeChange: handlePageSizeChange,
        }}
      />
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
